/**
 *  Author :  Bright
 *  Description : This class is to manage the chapters/contents of the book.
 */
package bookStore.eBook.android;
import bookStore.eBook.android.bookKEEPFORGUID.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;


public class ChapterManager {
	
	private static String TAG = "EBook:ChapterManager";
	private static String SEPARATOR = ":";
	private List<String> mChapters = new ArrayList<String>();
	private List<Integer> mIDs = new ArrayList<Integer>();
	private HashMap<String,Integer> mChapter2ID = new HashMap<String,Integer>();
	private String mBookName="";
	
	// singleton 
	private static ChapterManager mChapterManager = null;
	
	public static ChapterManager CreateChapterManager(Context context, int resourceID) throws Exception
	{
		mChapterManager = new ChapterManager(context, resourceID);
		return mChapterManager;
	}
	
	private ChapterManager(Context context, int resourceID) throws Exception
	{
		try {
			BufferedReader br=new BufferedReader(new InputStreamReader(context.getResources().openRawResource(resourceID)));
			mBookName = br.readLine();
			
			Class ownerClass = R.raw.class;//Class.forName("bookStore.eBook.android.R.raw");
			while(br.ready())
			{
				String string = br.readLine();
				if(string!=null && string.length()>0)
				{
					String[] pair = string.split(SEPARATOR);
					mChapters.add(pair[0]);
					
					Field field;
					field = ownerClass.getField(pair[pair.length-1]);
					Object property = field.get(ownerClass);
					int id = (Integer)property;

					mChapter2ID.put(pair[0], id);
					
					mIDs.add(id);
				}
			}
			br.close();
			
			
		} catch (IOException e1) {
			Toast.makeText(context, "Cannot find the content!",
					Toast.LENGTH_LONG).show();
			throw e1;
		}
	}
	
	public static ChapterManager getChapterManager()
	{
		return mChapterManager;
	}
	
	public String getBookName()
	{
		return mBookName;
	}
	
	public List<String> getAllChapters()
	{
		return mChapters;
	}
	
	public String getChapterName(int position)
	{
		return mChapters.get(position);
	}
	
	public int getChapterResourceID(String chapterName)
	{
		return mChapter2ID.get(chapterName);
	}
	
	public int getChapterResourceID(int position)
	{
		return mIDs.get(position);
	}
	
	public String getNextChapterName(String curChapterName)
	{
		int position = mChapters.indexOf(curChapterName);
		if(position < 0)
		{
			return "";
		}
		
		// if last one
		if(position == mChapters.size()-1)
			return curChapterName;
		
		return mChapters.get(position+1);
	}
	
	public boolean isLastChapter(String chapterName)
	{
		int position = mChapters.indexOf(chapterName);
		if(position == mChapters.size()-1)
		{
			return true;
		}
		
		return false;
	}
	
}
